package gui.utils;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

public class TextFieldNumbers extends JTextField {

	private class TextFieldNumbersKeyTyped implements KeyListener {

		private TextFieldNumbers tfn;

		public TextFieldNumbersKeyTyped(TextFieldNumbers tfn) {
			this.tfn = tfn;
		}

		@Override
		public void keyPressed(KeyEvent e) {
		}

		@Override
		public void keyReleased(KeyEvent e) {
		}

		@Override
		public void keyTyped(KeyEvent e) {
			if (!Character.isDigit(e.getKeyChar()))
				e.consume();
			if (maxNumbers != 0 && tfn.getText().length() >= maxNumbers)
				e.consume();
		}

	}

	private static final long serialVersionUID = 1L;

	private int maxNumbers = 0;

	public TextFieldNumbers() {
		super();
		this.addKeyListener(new TextFieldNumbersKeyTyped(this));
	}

	public TextFieldNumbers(int maxNumbers) {
		super();
		this.maxNumbers = maxNumbers;
		this.addKeyListener(new TextFieldNumbersKeyTyped(this));
	}
}
